type CallbackFunction = () => void

class CountdownTimer666 {
  private startTime: number
  private count: number
  private runTime: number
  private second: number
  private _second: number
  private loopTimer: NodeJS.Timeout | null
  private stopCallback: CallbackFunction | null
  private everySecondCallback: CallbackFunction | null

  constructor(
    second,
    stopCallback: CallbackFunction | null = null,
    everySecondCallback: CallbackFunction | null = null
  ) {
    this.startTime = 0
    this.count = 0
    this.runTime = 0
    this.second = second
    this._second = second
    this.loopTimer = null
    this.stopCallback = stopCallback
    this.everySecondCallback = everySecondCallback
  }

  private resetDefaultValue(): void {
    this.startTime = Date.now()
    this.count = 0
    this.runTime = 0
    this.second = this._second
  }

  public getDownSecond(): number {
    return this.second
  }

  public start(): void {
    this.resetDefaultValue()
    this.loop()
  }

  public end(): void {
    if (this.loopTimer !== null) {
      clearTimeout(this.loopTimer)
      this.loopTimer = null
      if (this.stopCallback && typeof this.stopCallback === 'function') {
        this.stopCallback()
        this.resetDefaultValue()
      }
    }
  }

  private loop(): void {
    this.runTime = Date.now()
    const offsetTime: number = this.runTime - (this.startTime + this.count * 1000)
    this.count++
    let nextTime: number = 1000 - offsetTime
    nextTime = nextTime > 0 ? nextTime : 0

    console.log('nextTime', nextTime, this.second)

    // 处理逻辑区域 ---- s
    console.log('时间差：' + offsetTime, '，下一次需要时间：' + nextTime)
    if (this.second <= 0) {
      this.end()
      this.resetDefaultValue()

      return
    }
    this.second--

    if (this.everySecondCallback) {
      this.everySecondCallback()
    }

    // 处理逻辑区域 ---- e
    this.loopTimer = setTimeout(() => this.loop(), 1000)
  }
}

export default CountdownTimer666
// 使用方式
// const countdown = new CountdownTimer()
// countdown.start()
// 在需要结束的地方调用
// countdown.end();
